package main

import (
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type User struct {
	Id       int    `json:"id"`
	UserName string `json:"username"`
	PassWord string `json:"password"`
}

func QueryUser(c *gin.Context) {
	log.Println(">>> QueryUser function start  <<<")
	var u User
	//
	userId, err := strconv.Atoi(c.Query("id"))
	u.Id = userId
	checkError(err)

	log.Println("data: ", u)

	c.JSON(http.StatusOK, gin.H{
		"message": "query successful",
		"data":    u,
	})
}

// CreateUser 创建用户
func CreateUser(c *gin.Context) {
	log.Println(">>> CreateUser function start  <<<")
	userName := c.PostForm("username")
	log.Println(userName)

	c.JSON(http.StatusOK, gin.H{
		"message": "create successful",
	})
}

/*
 * @Author: Daived
 * @DateTime: 2020/11/28 1:54 下午
 * @Remark: 解析json参数，注意结构体参数开头需大写
 */

func DeleteUser(c *gin.Context) {
	log.Println(">>> DeleteUser function start  <<<")
	var info User
	err := c.BindJSON(&info)
	checkError(err)
	log.Printf("info: %#v\n", info)

	c.JSON(http.StatusOK, gin.H{
		"message": "delete successful",
	})

}

/*
 * @Author: Daived
 * @DateTime: 2020/11/28 1:54 下午
 * @Remark: 解析Path Variable参数
 */

func UpdateUser(c *gin.Context) {
	log.Println(">>> UpdateUser function start  <<<")
	id := c.Param("id")
	log.Println(id)
	c.JSON(http.StatusOK, gin.H{
		"message": "update successful",
	})

}

func checkError(e error) {
	if e != nil {
		log.Println(e)
	}
}

func main() {
	// Engin
	r := gin.Default()

	// 路由组
	user := r.Group("/user")
	{ // 请求参数在请求路径上
		user.GET("/query", QueryUser)       // 查询用户
		user.POST("/create", CreateUser)    // 创建用户
		user.PUT("/update/:id", UpdateUser) // 修改用户
		user.DELETE("/delete", DeleteUser)  // 删除用户
	}

	r.Run()
}
